package cn.cyl.user.service.impl;

import cn.cyl.basic.exception.BusinessException;
import cn.cyl.basic.service.impl.BaseServiceImpl;
import cn.cyl.basic.util.Md5Utils;
import cn.cyl.basic.util.StrUtils;
import cn.cyl.user.domain.Logininfo;
import cn.cyl.user.domain.User;
import cn.cyl.user.mapper.LogininfoMapper;
import cn.cyl.user.mapper.UserMapper;
import cn.cyl.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.net.www.MessageHeader;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Transactional
    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.loadOne(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadOne(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
        super.update(user);
    }

    @Transactional
    @Override
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadOne(id);

        //删除user
        super.del(id);

        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());



        super.del(id);
    }

    @Transactional
    @Override
    public void save(User user) {

        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    @Transactional
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String repwd = map.get("repwd");

        //判断空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) ||
            StringUtils.isEmpty(pwd)||StringUtils.isEmpty(repwd)){
            throw new BusinessException("信息不能为空");
        }
        //判断两次密码
        if(!pwd.equals(repwd)){
            throw new BusinessException("两次密码不相同");
        }
        //判断手机验证码是否过期
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj==null){
            throw new BusinessException("验证码过期请重新获取");
        }
        //手机验证是否正确
        //redis中手机验证码的存储格式[业务键: 手机号码 - 验证码: 时间]
        if(!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("验证码输入错误");
        }


        //二: 添加到数据库
        //当将一个对象转换成另外一个对象的时候，而且代码量大的时候就用obj20bj
        User user = map2User(map);
        Logininfo logininfo=user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);
        //2.再添加t user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }

    @Transactional
    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String pwd = map.get("pwd");
        String repwd = map.get("repwd");
        //检验空值
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd) ||StringUtils.isEmpty(repwd)){
            throw new BusinessException("信息不能为空");
        }
        //校验邮箱
        User user=userMapper.loadByEmail(email);
        if(user!=null){
            throw new BusinessException("该邮箱已经被注册");
        }

        //密码校验
        if(!pwd.equals(repwd)){
            throw new BusinessException("两次密码不一致");
        }


        User user1 = new User();
        Logininfo logininfo = new Logininfo();


        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        logininfo.setEmail(email);
        logininfo.setUsername(email);
        logininfo.setSalt(salt);
        logininfo.setPassword(md5Pwd);
        logininfo.setDisable(true);
        logininfo.setType(1);
        logininfoMapper.save(logininfo);

        user1.setLogininfoId(logininfo.getId());
        user1.setEmail(email);
        user1.setUsername(email);
        user1.setSalt(salt);
        user1.setPassword(md5Pwd);
        user1.setState(0);
        userMapper.save(user1);

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");

        helper.setFrom("1175864373@qq.com");
        helper.setSubject("邮箱注册成功");
        helper.setText("<h1>邮箱注册成功</h1><a href='http://127.0.0.1:8080/user/register/"+email+"'>点击激活</a>",true);
        helper.setTo(email);
        javaMailSender.send(message);
        System.out.println(email);

    }

    /**
     * 点击邮件激活
     * @param email
     */
    @Transactional
    @Override
    public void active(String email) {
       User user= userMapper.active(email);
       user.setState(1);
        userMapper.update(user);

    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);

        return logininfo;
    }

    private User map2User(Map<String, String> map) {
        User user = new User();
        user.setUsername(map.get("phone"));
        user.setPhone(map.get("phone"));
        String salt = StrUtils.getComplexRandomString(32);
        String md5pwd = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        user.setState(1);
        return user;
    }
}
